//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { NodeEditPanelProps } from './common';
import { is_empty_doc, ReadOnlyEditor, useCommonEditor } from '@/components/Editor';
import { useRoadmapStores } from '../../store';
import { EXTRA_LINK_ARTICLE, EXTRA_LINK_COURSE, EXTRA_LINK_TEST, EXTRA_LINK_VIDEO, EXTRA_LINK_WEBSITE, type ExtraLinkItem } from "@/api/roadmap_content";
import { TOPIC_STATE_DOING, TOPIC_STATE_DONE, TOPIC_STATE_SKIP, remove_state, set_state } from '@/api/roadmap_state';
import { Button, Card, Form, List, message, Modal, Popover, Segmented, Space } from 'antd';
import { request } from '@/utils/request';
import { open as shell_open } from '@tauri-apps/api/shell';
import type { NoteInfo } from "@/api/roadmap_user";
import { set_note, remove_note } from "@/api/roadmap_user";
import { FILE_OWNER_TYPE_NONE } from '@/api/fs';
import { CloseOutlined, DeleteOutlined, EditOutlined, MoreOutlined, SaveOutlined } from '@ant-design/icons';
import CsdnIcon from '@/assets/logos/csdn.ico';
import JuejinIcon from '@/assets/logos/juejin.png';
import BilibiliIcon from '@/assets/logos/bilibili.ico';
import BaiduIcon from '@/assets/logos/baidu.ico';


interface NoteModalProps {
    nodeId: string;
}

const NoteModal = observer((props: NoteModalProps) => {
    const roadmapStore = useRoadmapStores();

    const [noteInfo, setNoteInfo] = useState<NoteInfo | null>(null);
    const [inEdit, setInEdit] = useState(false);

    const { editor, editorRef } = useCommonEditor({
        content: "",
        fsId: "",
        ownerType: FILE_OWNER_TYPE_NONE,
        ownerId: roadmapStore.roadmapId,
        historyInToolbar: false,
        clipboardInToolbar: false,
        commonInToolbar: true,
        pubResInToolbar: false,
    });

    const getTitle = () => {
        if (noteInfo == null) {
            return "创建学习笔记";
        } else {
            if (inEdit) {
                return "更新学习笔记";
            } else {
                return "查看学习笔记";
            }
        }
    };

    const setNote = async () => {
        const content = editorRef.current?.getContent() ?? { type: "doc" };
        if (is_empty_doc(content)) {
            message.warn("学习笔记是空的");
            return;
        }
        await request(set_note({
            session_id: roadmapStore.sessionId,
            roadmap_id: roadmapStore.roadmapId,
            node_id: props.nodeId,
            content: JSON.stringify(content),
        }));
        roadmapStore.onUpdateNote(props.nodeId);
        message.info("保存成功");
        if (inEdit) {
            setInEdit(false);
        }
    };

    const removeNote = async () => {
        await request(remove_note({
            session_id: roadmapStore.sessionId,
            roadmap_id: roadmapStore.roadmapId,
            node_id: props.nodeId,
        }));
        roadmapStore.onUpdateNote(props.nodeId);
        message.info("删除成功");
        roadmapStore.showNote = false;
    };

    useEffect(() => {
        const tmpInfo = roadmapStore.noteList.find(item => item.node_id == props.nodeId);
        setNoteInfo(tmpInfo ?? null);
    }, [roadmapStore.noteList]);

    useEffect(() => {
        if (editorRef.current != null && inEdit && noteInfo != null) {
            editorRef.current.setContent(noteInfo.content);
        }
    }, [noteInfo, inEdit, editorRef.current]);

    return (
        <Modal open mask={false} closable={false} width="calc(100vw - 200px)"
            footer={null} bodyStyle={{ padding: "0px 0px" }}>
            <Card title={getTitle()} bordered={false}
                extra={
                    <>
                        {noteInfo == null && (
                            <Space size="large">
                                <Button type="primary" icon={<SaveOutlined />} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setNote();
                                }}>保存</Button>
                                <Button type='text' icon={<CloseOutlined style={{ fontSize: "20px" }} />} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    roadmapStore.showNote = false;
                                }} />
                            </Space>
                        )}
                        {noteInfo != null && (
                            <>
                                {inEdit == true && (
                                    <Space size="large">
                                        <Button type='default' onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setInEdit(false);
                                        }}>取消</Button>
                                        <Button type="primary" icon={<SaveOutlined />} onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setNote();
                                        }}>保存</Button>
                                    </Space>
                                )}
                                {inEdit == false && (
                                    <Space size="large">
                                        <Button type='primary' icon={<EditOutlined />} onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setInEdit(true);
                                        }}>更新</Button>
                                        <Popover placement='bottom' trigger="click" content={
                                            <Space direction='vertical'>
                                                <Button type="link" danger icon={<DeleteOutlined />} onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    removeNote();
                                                }}>删除</Button>
                                            </Space>
                                        }>
                                            <MoreOutlined />
                                        </Popover>
                                        <Button type='text' icon={<CloseOutlined style={{ fontSize: "20px" }} />} onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            roadmapStore.showNote = false;
                                        }} />
                                    </Space>
                                )}
                            </>
                        )}
                    </>
                }>
                {noteInfo == null && (
                    <div className='_orgPostContext'>
                        {editor}
                    </div>
                )}
                {noteInfo != null && (
                    <>
                        {inEdit == true && (
                            <div className='_orgPostContext'>
                                {editor}
                            </div>
                        )}
                        {inEdit == false && (
                            <div className='_orgPostContext'>
                                <ReadOnlyEditor content={noteInfo.content} />
                            </div>
                        )}
                    </>
                )}
            </Card>
        </Modal>
    );
});

const TopicNodeViewPanel = (props: NodeEditPanelProps) => {
    const roadmapStore = useRoadmapStores();

    const [content, setContent] = useState("");
    const [linkList, setLinkList] = useState<ExtraLinkItem[]>([]);
    const [userState, setUserState] = useState<"none" | "doing" | "done" | "skip">("none");

    const loadNodeData = () => {
        const curNode = roadmapStore.getNode(props.nodeId);
        if (curNode == undefined) {
            return;
        }
        setContent(curNode.basic_info.node_data.TopicData?.content ?? "");
        setLinkList(curNode.basic_info.node_data.TopicData?.link_list ?? []);
    };

    const genQueryData = () => {
        const curNode = roadmapStore.getNode(props.nodeId);
        if (curNode == undefined) {
            return "";
        }
        const data = curNode.basic_info.node_data.TopicData;
        if (data == undefined) {
            return "";
        }
        return `${roadmapStore.roadmapInfo?.basic_info.title ?? ""} ${data.title}`;
    };

    const loadState = async () => {
        const curStateInfo = roadmapStore.stateList.find(item => item.node_id == props.nodeId);
        if (curStateInfo == undefined) {
            setUserState("none");
            return;
        }
        const curState = curStateInfo.basic_info.state_data.TopicState?.state ?? TOPIC_STATE_DOING;
        if (curState == TOPIC_STATE_DOING) {
            setUserState("doing");
        } else if (curState == TOPIC_STATE_DONE) {
            setUserState("done");
        } else if (curState == TOPIC_STATE_SKIP) {
            setUserState("skip");
        }
    };

    const updateUserState = async (newState: "none" | "doing" | "done" | "skip") => {
        if (newState == "none") {
            await request(remove_state({
                session_id: roadmapStore.sessionId,
                roadmap_id: roadmapStore.roadmapId,
                node_id: props.nodeId,
            }));
        } else {
            const curNode = roadmapStore.getNode(props.nodeId);
            if (curNode == undefined) {
                return;
            }

            let topicState = TOPIC_STATE_DOING;
            if (newState == "done") {
                topicState = TOPIC_STATE_DONE;
            } else if (newState == "skip") {
                topicState = TOPIC_STATE_SKIP;
            }

            await request(set_state({
                session_id: roadmapStore.sessionId,
                roadmap_id: roadmapStore.roadmapId,
                node_id: props.nodeId,
                basic_info: {
                    state_data: {
                        TopicState: {
                            state: topicState,
                            title: curNode.basic_info.node_data.TopicData?.title ?? "",
                        },
                    },
                },
            }));
        }
        roadmapStore.onUpdateNodeState(props.nodeId);
    };



    useEffect(() => {
        loadNodeData();
    }, [props.nodeId]);

    useEffect(() => {
        loadState();
    }, [props.nodeId, roadmapStore.stateList]);

    return (
        <div>
            <div style={{ position: "fixed", top: "10px", right: "10px" }}>
                <Form layout='inline'>
                    <Form.Item>
                        <Button type="primary" style={{ marginRight: "30px" }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            roadmapStore.showNote = true;
                        }}>
                            {roadmapStore.noteList.map(item => item.node_id).includes(props.nodeId) ? "查看学习笔记" : "创建学习笔记"}
                        </Button>
                    </Form.Item>
                    <Form.Item label="学习状态">
                        <Segmented options={[
                            {
                                label: "未学习",
                                value: "none",
                            },
                            {
                                label: "学习中",
                                value: "doing",
                            },
                            {
                                label: "已掌握",
                                value: "done",
                            },
                            {
                                label: "忽略",
                                value: "skip",
                            }
                        ]} value={userState} onChange={value => updateUserState(value as "none" | "doing" | "done" | "skip")} />
                    </Form.Item>
                </Form>
            </div>
            <div>
                <ReadOnlyEditor content={content} />
            </div>
            {linkList.length > 0 && (
                <Card title="额外链接" bordered={false}
                    headStyle={{ fontSize: "16px", fontWeight: 700, backgroundColor: "#fafafa" }}>
                    <List rowKey="link_id" dataSource={linkList} pagination={false}
                        renderItem={linkItem => (
                            <List.Item>
                                <Space>
                                    <div style={{ width: "100px" }}>
                                        {linkItem.link_type == EXTRA_LINK_ARTICLE && "文章"}
                                        {linkItem.link_type == EXTRA_LINK_VIDEO && "视频"}
                                        {linkItem.link_type == EXTRA_LINK_TEST && "评估"}
                                        {linkItem.link_type == EXTRA_LINK_COURSE && "课程"}
                                        {linkItem.link_type == EXTRA_LINK_WEBSITE && "网址"}
                                    </div>
                                    <a onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        shell_open(linkItem.link_url);
                                    }}>{linkItem.link_title == "" ? linkItem.link_url : linkItem.link_title}</a>
                                </Space>
                            </List.Item>
                        )} />
                </Card>
            )}
            <Card title="外部资源" bordered={false}
                headStyle={{ fontSize: "16px", fontWeight: 700, backgroundColor: "#fafafa" }}>
                <Space>
                    <Button type="link" icon={<img src={CsdnIcon} style={{ width: "20px", marginRight: "4px" }} />}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const query = genQueryData();
                            shell_open(`https://so.csdn.net/so/search?q=${encodeURIComponent(query)}`);
                        }}>CSDN</Button>
                    <Button type="link" icon={<img src={JuejinIcon} style={{ width: "20px", marginRight: "4px" }} />}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const query = genQueryData();
                            shell_open(`https://juejin.cn/search?query=${encodeURIComponent(query)}`);
                        }}>稀土掘金</Button>
                    <Button type="link" icon={<img src={BilibiliIcon} style={{ width: "20px", marginRight: "4px" }} />}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const query = genQueryData();
                            shell_open(`https://search.bilibili.com/all?keyword=${encodeURIComponent(query)}`);
                        }}>哔哩哔哩</Button>
                    <Button type="link" icon={<img src={BaiduIcon} style={{ width: "20px", marginRight: "4px" }} />}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const query = genQueryData();
                            shell_open(`https://www.baidu.com/s?wd=${encodeURIComponent(query)}`);
                        }}>百度</Button>
                </Space>
            </Card>
            {roadmapStore.showNote == true && (
                <NoteModal nodeId={props.nodeId} />
            )}
        </div>
    );
};

export default observer(TopicNodeViewPanel);